package ajaxjs.net.upload;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class BaseUpload {
	public HttpServletRequest request;
	public BaseUpload(HttpServletRequest request) {
		this.request = request;
	}
	
	/**
	 * 保存上传的文件数据
	 * @param formDataLength
	 * @param in
	 * @return
	 * @throws IOException
	 */
	private byte[] getBytes() throws IOException{
		DataInputStream in = new DataInputStream(request.getInputStream());
		int byteRead = 0, totalRead = 0, formDataLength = request.getContentLength();
		byte dateBytes[] = new byte[formDataLength];
	    
		while(totalRead < formDataLength){
			byteRead = in.read(dateBytes, totalRead, formDataLength);
	        totalRead += byteRead;
	    }	
	 
		in.close();
			 
		return dateBytes;
	}
	
	/**
	 * 取得数据分割字符串
	 * @param contentType
	 * @return
	 */
	private static String getBoundary(String contentType){	
		int lastIndex = contentType.lastIndexOf("="); 
		// 数据分割线开始位置boundary=---------------------------
		return contentType.substring(lastIndex + 1, contentType.length());
	}
	
	/**
	 * 分析位置
	 * @param contentType
	 * @param dateBytes
	 * @return
	 */
	private static int[] getPos(String contentType, byte[] dateBytes){
	    // 计算开头数据头占用的长度
	    int startPos;
	    startPos = byteIndexOf(dateBytes, "filename=\"".getBytes(), 0);
	    startPos = byteIndexOf(dateBytes, "\n".getBytes(), startPos) + 1;  //遍历掉3个换行符到数据块
	    startPos = byteIndexOf(dateBytes, "\n".getBytes(), startPos) + 1;
	    startPos = byteIndexOf(dateBytes, "\n".getBytes(), startPos) + 1;
	    
	    // 边界位置
	    String boundary = getBoundary(contentType);
	    int endPos = byteIndexOf(dateBytes, boundary.getBytes(), (dateBytes.length - startPos)) - 4;
	    
		return new int[]{startPos, endPos};
	}
	
	/**
	 * 在字节数组里查找某个字节数组，找到返回>=0，未找到返回-1
	 * @param data
	 * @param search
	 * @param start
	 * @return
	 */
	private static int byteIndexOf(byte[] data, byte[] search, int start){
	    int index = -1, len = search.length;
	    
	    for(int i = start, j = 0; i < data.length; i++){        
	        int temp = i;
	        j = 0;
	        while(data[temp] == search[j]){
	            // System.out.println((j+1)+",值："+data[temp]+","+search[j]);
	            // 计数
	            j++;
	            temp++;
	            if(j == len){
	              index = i;
	              return index;
	            }             
	        }
	    }
	    
	    return index;
	}	
	
	
	public String upload(){
		byte[] dateBytes = null;
		
		try {
			dateBytes = getBytes();
		} catch (IOException e) {
			request.setAttribute("err", "获取流失败！");
			e.printStackTrace();
			return null;
		}
		
		// 取得客户端上传的数据类型
		String contentType = request.getContentType();
		int[] pos = getPos(contentType, dateBytes);
		int startPos = pos[0], endPos = pos[1];
		
		// 创建文件
		String fileName = createFile(dateBytes, startPos, endPos - startPos);
		getFormData(createFile(dateBytes));
		return fileName;
	}
	
	public String createFile(byte[] dateBytes, int startPos, int offsetPos) {
		return null;
	}

	public String createFile(byte[] dateBytes){
		String data;
		try {
			data = new String(dateBytes, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
			return null;
		}
		
		return data;
	}
	
	public String getFileName(String data){
		return null;
	}
	
	public Map<String, String> formData = new HashMap<String, String>();
	public void getFormData(String formStr) {
		String b = getBoundary(request.getContentType());
		String[] arr = formStr.split(b);
		for(String item : arr){
			if(item.indexOf("Content-Type: ") != -1 && item.indexOf("filename=\"") != -1)
				continue;
			else if(item.indexOf("Content-Disposition: form-data;") != -1){
			    // Get the content disposition, should be "form-data"
			    int start = item.toLowerCase().indexOf("content-disposition: ");
			    int end = item.indexOf(";");
			    // Get the field name
			    start = item.indexOf("name=\"", end);  // start at last semicolon
			    end = item.indexOf("\"", start + 7);   // skip name=\"
			    String name = item.substring(start + 6, end);
			    
			    String value = item.substring(item.indexOf(name + "\"") + name.length() + 1, item.length());
			    value = value.substring(0, value.lastIndexOf("\n")); // remove the last line
			    value = value.trim();
			
				System.out.println(name + ":::::" + value);
			    
			    formData.put(name, value);
			}
		}
	}
}